package com.trw.trp.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.trw.trp.bean.ListBean;
import com.trw.trp.dao.DaoFactory;
import com.trw.trp.dao.ListDao;
import com.trw.trp.dao.ModelDao;
import com.trw.trp.msg.ResultMessage;
import com.trw.trp.util.TRPConstants;

public class ListManagementAction extends AbstractAction {

	private long listId;

	public long getListId() {
		return listId;
	}

	public void setListId(long listId) {
		this.listId = listId;
	}

	public String execute() {
		return SUCCESS;
	}

	public void getLists() throws IOException {
		ListDao dao = DaoFactory.getListDao();
		List<ListBean> list = dao.getAllLists();
		writeJSON(list);
	}

	public void getList() throws IOException {
		ListDao dao = DaoFactory.getListDao();
		ListBean list = dao.getList(listId);
		writeJSON(list);
	}

	public void saveList() throws IOException {
		ResultMessage msg = new ResultMessage();
		boolean success = false;
		String itemNames = getParamFromRequest("itemNames");
		if (!StringUtils.isEmpty(itemNames)) {
			ListBean list = new ListBean();
			list.setId(listId);
			List<ListBean.ItemBean> itemList = new ArrayList<ListBean.ItemBean>();
			list.setItemList(itemList);
			String[] itemArray = itemNames.split(TRPConstants.COMMA);
			for (String item : itemArray) {
				ListBean.ItemBean itemBean = new ListBean.ItemBean();
				itemBean.setName(item);
				itemList.add(itemBean);
			}
			ListDao dao = DaoFactory.getListDao();
			success = dao.saveList(list);
			refreshCache();
		}
		msg.setState(success ? ResultMessage.SUCCESS : ResultMessage.FAILED);
		writeJSON(msg);
	}
	
	private void refreshCache(){
		ListDao dao = DaoFactory.getListDao();
		List<Long> modelIdList = dao.getAffectedModels(listId);
		ModelDao modelDao = DaoFactory.getModelDao();
		for(long modelId:modelIdList){
			modelDao.removeDetail(modelId);
		}
	}

}
